package com.kk.controller;



import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kk.common.lang.Result;
import com.kk.entity.Blog;
import com.kk.jwt.JwtUser;
import com.kk.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author kk
 * @since 2020-06-11
 */
@RestController
@CrossOrigin
public class BlogController {
    @Autowired
    private BlogService blogService;

    //获取所有博客列表
    @GetMapping("/blogs")
    public Result blogs(Integer currentPage) {
        if(currentPage == null || currentPage < 1) currentPage = 1;
        Page page = new Page(currentPage, 7);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>()
                .orderByDesc("create_time"));
        return Result.success(pageData);
    }
    //获取个人博客列表
    @GetMapping("/myblogs")
    public Result myBlogs(Integer currentPage,Long id) {
        if(currentPage == null || currentPage < 1) currentPage = 1;
        Page page = new Page(currentPage, 7);
        IPage pageData = blogService.page((IPage<Blog>) page, new QueryWrapper<Blog>()
                .eq("user_id",id)
                .orderByDesc("create_time"));
        return Result.success(pageData);
    }

    //获取详情
    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客已删除！");
        return Result.success(blog);
    }
    //添加博客


    //编辑和添加博客 （复用）
    @PreAuthorize("hasAuthority('user')")
    @PostMapping("/blog/edit")
    public Result edit(@RequestBody Blog blog) {
        //System.out.println(blog.toString());
        //获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser hostholder = (JwtUser) authentication.getPrincipal();
        System.out.println(hostholder);
        System.out.println(blog);
        Blog temp = null;
        //若id不为空则是编辑blog
        if(blog.getId() != null) {
            temp = blogService.getById(blog.getId());
            //判断是否为本人
            Assert.isTrue(temp.getUserId() == hostholder.getId(), "没有权限编辑!");
            //若查询不到blog，则为发表文章
        }else {
            temp = new Blog();
            temp.setUserId(hostholder.getId());
            temp.setCreateTime(new Date());
            temp.setStatus(0);
        }
        //修改的部分是 title content description
        BeanUtil.copyProperties(blog, temp, "id","userId","createTime","status");
        blogService.saveOrUpdate(temp);
        return Result.success(200,"编辑成功!", null);
    }

    //删除博客
    @PreAuthorize("hasAuthority('user')")
    @GetMapping("/delblog/{id}")
    public Result delete(@PathVariable(name = "id") Long id) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser hostholder = (JwtUser) authentication.getPrincipal();
        Blog blog = blogService.getById(id);
        Assert.isTrue(blog.getUserId()==hostholder.getId(),"没有权限删除!");
        blogService.removeById(id);
        return Result.success("该博客已删除");
    }
}

